/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 16/06/2011, 17:06:51
 */
package datainsert.frames;

import datainsert.frames.help.HelpFrame;
import datainsert.DBExceptionToken;
import datainsert.ExceptionToken;
import datainsert.controlers.*;
import datainsert.controlers.ContentControler.ComboControler;
import datainsert.controlers.ContentControler.ListControler;
import datainsert.controlers.ContentControler.TableControler;
import datainsert.dbinterface.*;
import datainsert.TableRenderers;
import datainsert.dbinterface.DBInterface;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 * Interface principal do aplicativo
 * @author Yule Vaz
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Controle de conteúdo de importaçao e de componentes
     */
    public final ContentControler contentControler = new ContentControler();
    /**
     * Renderizador de tabela
     */
    public final TableRenderers tableRenderers = new TableRenderers();
    /**
     * Controlador dos caracteres de divisão de dados
     */
    public ParseMaskControler parseMask;
    
    /** Creates new form MainFrame */
    /**
     * Constrói esta interface
     */
    public MainFrame() {
   
//        dbinterface = new DBInterface("irrigap_terralib_final","postgres","postgres");
        dbinterface = new DBInterface();
        currentNo = new DBNo();
        canais = new DBCanal[15];
        parseMask = new ParseMaskControler();
        initComponents();
        ActionListener obs = new MainFrame.MainActuator();
        ListenersControler.addButtonActionListener(obs, jbBrowse);
        ListenersControler.addButtonActionListener(obs, jbAddDispositivos);
        ListenersControler.addButtonActionListener(obs, jbRmDispositivos);
        ListenersControler.addComboActionListener(obs, jcmbNo);
        ListenersControler.addButtonActionListener(obs, jbInserir); 
        ListenersControler.addMenuActionListener(obs,jmenuAbrir);
        ListenersControler.addMenuActionListener(obs, jmenuFechar);
        ListenersControler.addMenuActionListener(obs, jmenuSair);
        ListenersControler.addMenuActionListener(obs, jmenuAbrirConexao);
        ListenersControler.addMenuActionListener(obs, jmenuFecharConexao);
        ListenersControler.addMenuActionListener(obs, jmenuMask);
        ListenersControler.addMenuActionListener(obs, jmenuRemover);
        ListenersControler.addMenuActionListener(obs, jmenuAjuda) ;
//        ContentControler.setTableRenderer(jtabDados);
        
    }
    
    private MainFrame getMainFrame() {
        return this;
    }
    
    /**
     * Verifica se o aplicativo está conectada à base de dados
     * @return 
     */
    public boolean isConnected() {
        return dbinterface.isConnected();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpanInput = new javax.swing.JPanel();
        jcmbNo = new javax.swing.JComboBox();
        /*DBNo [] nos = DBNo.allFromDatabase(dbinterface.getConn());
        String [] modelStr = new String[nos.length+1];

        modelStr[0] = "";

        for ( int i = 1; i < modelStr.length; i++ )
        modelStr[i] = String.valueOf(nos[i-1].getId()) + ":    " +
        nos[i-1].getCod() + ":    " + nos[i-1].getTable();*/
        jScrollPane2 = new javax.swing.JScrollPane();
        jtabCanais = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jpanTable = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtabDados = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jlstRmDispositivos = new javax.swing.JList();
        jbAddDispositivos = new javax.swing.JButton();
        jbRmDispositivos = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtabDispositivos = new javax.swing.JTable();
        jbBrowse = new javax.swing.JButton();
        jtxtBrowse = new javax.swing.JTextField();
        jbInserir = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jcmbDate = new javax.swing.JComboBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jmenuArquivo = new javax.swing.JMenu();
        jmenuAbrir = new javax.swing.JMenuItem();
        jmenuFechar = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jmenuMask = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jmenuSair = new javax.swing.JMenuItem();
        jmenuConexao = new javax.swing.JMenu();
        jmenuAbrirConexao = new javax.swing.JMenuItem();
        jmenuFecharConexao = new javax.swing.JMenuItem();
        jmnDados = new javax.swing.JMenu();
        jmenuRemover = new javax.swing.JMenuItem();
        jmnAjuda = new javax.swing.JMenu();
        jmenuSobre = new javax.swing.JMenuItem();
        jmenuAjuda = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jpanInput.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleção da tabela de dados"));
        jpanInput.setPreferredSize(new java.awt.Dimension(800, 200));

        /*ComboControler cmbControler = contentControler.getComboControler();
        cmbControler.setContent(jcmbNo, modelStr);*/

        jtabCanais.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod. Dispositivo", "Rótulo", "Canal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jtabCanais);

        jLabel1.setText("Tabela de dados:");

        jLabel2.setText("Guia de dispositivos:");

        javax.swing.GroupLayout jpanInputLayout = new javax.swing.GroupLayout(jpanInput);
        jpanInput.setLayout(jpanInputLayout);
        jpanInputLayout.setHorizontalGroup(
            jpanInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanInputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpanInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jcmbNo, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 1125, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpanInputLayout.setVerticalGroup(
            jpanInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanInputLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcmbNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
                .addContainerGap())
        );

        jpanTable.setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção de dados"));
        jpanTable.setPreferredSize(new java.awt.Dimension(800, 400));

        jtabDados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jtabDados.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jtabDados.setColumnSelectionAllowed(true);
        jtabDados.setDragEnabled(true);
        jtabDados.setEnabled(false);
        jScrollPane1.setViewportView(jtabDados);

        jScrollPane3.setViewportView(jlstRmDispositivos);

        jbAddDispositivos.setText(">>");

        jbRmDispositivos.setText("<<");

        jtabDispositivos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Dispositivos", "Canal"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane4.setViewportView(jtabDispositivos);

        jbBrowse.setText("Arquivo");

        jbInserir.setText("Inserir Dados");

        jLabel3.setText("Dados do arquivo importado:");

        jLabel4.setText("Dispositivos do arquivo:");

        jLabel5.setText("Dispositivos à inserir:");

        jcmbDate.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Formatar Data", "DD/MM/YYYY", "MM/DD/YYYY", "YYYY/MM/DD", "DD/MM/YY", "MM/DD/YY", "YY/MM/DD" }));

        javax.swing.GroupLayout jpanTableLayout = new javax.swing.GroupLayout(jpanTable);
        jpanTable.setLayout(jpanTableLayout);
        jpanTableLayout.setHorizontalGroup(
            jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanTableLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jpanTableLayout.createSequentialGroup()
                            .addComponent(jbBrowse)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jtxtBrowse))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 602, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addGroup(jpanTableLayout.createSequentialGroup()
                        .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jcmbDate, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jbRmDispositivos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jbAddDispositivos, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))))
                .addGap(6, 6, 6)
                .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jbInserir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
                .addContainerGap())
        );
        jpanTableLayout.setVerticalGroup(
            jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpanTableLayout.createSequentialGroup()
                .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpanTableLayout.createSequentialGroup()
                        .addGap(151, 151, 151)
                        .addComponent(jbAddDispositivos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbRmDispositivos))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpanTableLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpanTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbInserir)
                    .addComponent(jtxtBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcmbDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jmenuArquivo.setText("Arquivo");

        jmenuAbrir.setText("Abrir");
        jmenuArquivo.add(jmenuAbrir);

        jmenuFechar.setText("Fechar");
        jmenuArquivo.add(jmenuFechar);
        jmenuArquivo.add(jSeparator2);

        jmenuMask.setText("Definir Separadores");
        jmenuArquivo.add(jmenuMask);
        jmenuArquivo.add(jSeparator1);

        jmenuSair.setText("Sair");
        jmenuArquivo.add(jmenuSair);

        jMenuBar1.add(jmenuArquivo);

        jmenuConexao.setText("Conexão");

        jmenuAbrirConexao.setText("Abrir Conexão");
        jmenuConexao.add(jmenuAbrirConexao);

        jmenuFecharConexao.setText("Fechar Conexão");
        jmenuConexao.add(jmenuFecharConexao);

        jMenuBar1.add(jmenuConexao);

        jmnDados.setText("Dados");

        jmenuRemover.setText("Remover");
        jmnDados.add(jmenuRemover);

        jMenuBar1.add(jmnDados);

        jmnAjuda.setText("Ajuda");

        jmenuSobre.setText("Sobre");
        jmnAjuda.add(jmenuSobre);

        jmenuAjuda.setText("Ajuda");
        jmnAjuda.add(jmenuAjuda);

        jMenuBar1.add(jmnAjuda);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jpanTable, javax.swing.GroupLayout.Alignment.LEADING, 0, 1161, Short.MAX_VALUE)
                    .addComponent(jpanInput, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 1161, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jpanInput, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpanTable, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                MainFrame app = new MainFrame();
                app.setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JButton jbAddDispositivos;
    private javax.swing.JButton jbBrowse;
    private javax.swing.JButton jbInserir;
    private javax.swing.JButton jbRmDispositivos;
    private javax.swing.JComboBox jcmbDate;
    private javax.swing.JComboBox jcmbNo;
    private javax.swing.JList jlstRmDispositivos;
    private javax.swing.JMenuItem jmenuAbrir;
    private javax.swing.JMenuItem jmenuAbrirConexao;
    private javax.swing.JMenuItem jmenuAjuda;
    private javax.swing.JMenu jmenuArquivo;
    private javax.swing.JMenu jmenuConexao;
    private javax.swing.JMenuItem jmenuFechar;
    private javax.swing.JMenuItem jmenuFecharConexao;
    private javax.swing.JMenuItem jmenuMask;
    private javax.swing.JMenuItem jmenuRemover;
    private javax.swing.JMenuItem jmenuSair;
    private javax.swing.JMenuItem jmenuSobre;
    private javax.swing.JMenu jmnAjuda;
    private javax.swing.JMenu jmnDados;
    private javax.swing.JPanel jpanInput;
    private javax.swing.JPanel jpanTable;
    private javax.swing.JTable jtabCanais;
    private javax.swing.JTable jtabDados;
    private javax.swing.JTable jtabDispositivos;
    private javax.swing.JTextField jtxtBrowse;
    // End of variables declaration//GEN-END:variables
    /**
     * Janela de seleção de arquivo
     */
    private final javax.swing.JFileChooser jFileChooser1 = new javax.swing.JFileChooser();
    
    /**
     * Interface entre uma base de dados
     */
    private DBInterface dbinterface;
    /**
     * Objeto de representação da entidade nó (da base de dados) selecionada pelo usuário
     */
    private DBNo currentNo;
    
    /**
     * Objetos de representação das entidades canais referentes à entidade nó selecionada pelo usuário
     */
    private DBCanal [] canais;
 
    /**
     * Abre o arquivo a ser importado
     */
    public void openFile() {
        
        if (parseMask.get().size() != 0) {
            File file;
            int returnVal = jFileChooser1.showOpenDialog(MainFrame.this);

            if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
                file = jFileChooser1.getSelectedFile();
                ExceptionToken expt = new ExceptionToken();
                Character [] c = new Character[parseMask.get().size()];
                parseMask.get().toArray(c);
                contentControler.loadFile(file,c,expt);
                if ( expt.getErrCount() == 0 ) {
                TableControler tbControler = contentControler.getTableControler();
                ComboControler cmbControler = contentControler.getComboControler();
                ListControler lstControler = contentControler.getListControler();
                //This is where a real application would open the file.
                TableUtils.removeAllContent(jtabDispositivos);
                jtxtBrowse.setText(file.getAbsolutePath());
                lstControler.addAllContent(jlstRmDispositivos);
                tbControler.setModel(tbControler.getModel(c), jtabDados);
             }
             else {
                    JOptionPane.showMessageDialog(null, expt.toString());
                    expt.reset();
                }

            }
        } else
            JOptionPane.showMessageDialog(null, "Não foi definido nenhum parâmetro de separação de dados. Defina em Arquivo -> Definir Separação.");
    }
    
    /**
     * Ouvinte da interface principal. Detecta eventos ocasionados pelo usuário e executa operações
     * dependendo de tais eventos
     */
    public class MainActuator implements ActionListener {

        /**
         * Executa uma ação dependendo do evento acionado
         * @param e Evento acionado
         */
        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == jbBrowse)
                openFile();

            
            if ( e.getSource() == jbAddDispositivos ) {
                ListControler lstControler = contentControler.getListControler();
                int [] index = jlstRmDispositivos.getSelectedIndices();
                ListModel lstModel = jlstRmDispositivos.getModel();
                TableColumn col;
                for ( int i = index.length-1; i >= 0; i-- ) {
                    col = jtabDados.getColumn(lstModel.getElementAt(index[i]));
                    jtabDados.addColumnSelectionInterval(col.getModelIndex(), col.getModelIndex());
                }
                jtabDados.setRowSelectionInterval(0, jtabDados.getRowCount()-2);
                //lstControler.addLst2Lst(jlstAddDispositivos, jlstRmDispositivos, index);
                lstControler.addLst2Table(jlstRmDispositivos, jtabDispositivos, index);
            }
            
            if ( e.getSource() == jbRmDispositivos ) {
                ListControler lstControler = contentControler.getListControler();
                TableControler tabControler = contentControler.getTableControler();
                int [] index = jtabDispositivos.getSelectedRows();
                TableModel tabModel = jtabDispositivos.getModel();
                TableColumn col;
                for ( int i = index.length-1; i >= 0; i-- ) {
                    col = jtabDados.getColumn(tabModel.getValueAt(index[i], 0));
                    jtabDados.removeColumnSelectionInterval(col.getModelIndex(), col.getModelIndex());
                }
                //lstControler.addLst2Lst(jlstRmDispositivos, jlstAddDispositivos, index);
                tabControler.addTable2Lst(jtabDispositivos, jlstRmDispositivos, index);
            }
            
            if ( e.getSource() == jcmbNo ) {

                if ( jcmbNo.getSelectedItem().toString().compareTo("") != 0 ) {
                    
                    TableRenderers tbRender = new TableRenderers();
                    int idx = 0;
                    int len = jcmbNo.getSelectedItem().toString().length();
                    String search = ":    ";
                    String base = jcmbNo.getSelectedItem().toString();
                    DBDispositivo disp = new DBDispositivo();
                    TableControler tbControler = contentControler.getTableControler();
                    
                    idx = base.indexOf(search);
                    currentNo.setId(Integer.valueOf(base.substring(0, idx)));
                    
                    base = base.substring(idx+search.length(),base.length());
                    
                    idx = base.indexOf(search);
                    currentNo.setCod(base.substring(0,idx));
                    
                    base = base.substring(idx+search.length(),base.length());
                    
                    currentNo.setTable(base);
                    
                    canais = DBCanal.allValidFromDatabase(dbinterface.getConn(), currentNo.getCod());
                    
                    String [] titles = new String[3];
                    titles[0] = "Cod. Dispositivo";
                    titles[1] = "Rótulo";
                    titles[2] = "Canal";
                    String [][] modelStr = new String[canais.length][3];
                    String [] ids = new String[canais.length+1];
                    
                    ids[0] = "";
                    for ( int i = 1; i < canais.length+1; i++ ) {
                        
                        if ( canais[i-1].getCod().compareTo("-1") != 0 ) {
                            disp.setCod(canais[i-1].getCod());
                            disp.inDatabase(dbinterface.getConn());
                            modelStr[i-1][0] = disp.getCod();
                            modelStr[i-1][1] = disp.getLabel();
                            modelStr[i-1][2] =  String.valueOf(canais[i-1].getId());
                            ids[i] = String.valueOf(canais[i-1].getId()) + " " + disp.getCod();
                        }
                        
                    }
                    
                    contentControler.setIds(ids);
                    tbControler.setModel(modelStr, titles, jtabCanais);
                    
                    if ( jtabDispositivos.getRowCount() != 0 )
                        tbRender.setCellToCombo(jtabDispositivos,ids,1);
                    
                }
                else { 
                    currentNo.setId(-1);
                    currentNo.setCod("");
                    currentNo.setTable("");
                }
                
            }
            
            if ( e.getSource() == jbInserir ) {
                
                if ( !contentControler.isFileAttached() ) {
                    JOptionPane.showMessageDialog(null, "Deve ser escolhido um arquivo de dados para a inserção.");
                }
                else if ( currentNo.getId() == -1 ) {
                    JOptionPane.showMessageDialog(null,"Deve ser escolhido um banco de dados para a inserção de dados.");
                }
                else if ( jcmbDate.getSelectedIndex() != 0 ) {

                    String msg =  "Deseja prosseguir com a insercão? "
                            + "\nVerifique se o formato de data foi escolhido corretamente.";
                    
                    if (parseMask.isDefault()) msg += "\nOs delimitadores de dados utilizados serão "
                            + "os delimitadores padrões (espaço e tabulação).";
                   
                    int opt = JOptionPane.showConfirmDialog(null,  msg);
                    
                    if ( opt == JOptionPane.YES_OPTION ) {
                    
                    String [] cols = new String[5];
                    String [] data = new String[5];
                    int valid = 0;
                    String date, hour;
                    String selected;
                    cols[0] = "canal_aquisicao";
                    cols[1] = "data";
                    cols[2] = "hora";
                    cols[3] = "dado";
                    cols[4] = "datanum";
                    int k;
                    int total = jtabDados.getRowCount();
                    double aux;
                    JComboBox renderer;
                    TableModel model;
                    DBExceptionToken expt = new DBExceptionToken();
                    DBExceptionToken exins = new DBExceptionToken();

                    for ( int i = 0; i < jtabDispositivos.getRowCount(); i++ ) {

                        selected = (String)jtabDispositivos.getValueAt(i,0);
                        renderer = (JComboBox)jtabDispositivos.getCellRenderer(i, 1);
                        model = jtabDispositivos.getModel();
                        data[0] = String.valueOf(model.getValueAt(i, 1));
                        data[0] = data[0].substring(0, data[0].indexOf(" "));

                        for ( k = 2; k < jtabDados.getColumnCount(); k++ ) {
                                   if ( selected.compareTo(jtabDados.getColumnName(k)) == 0 )
                                       break;
                        }

                        for ( int j = 0; j < jtabDados.getRowCount(); j++ ) {
                              date = (String)jtabDados.getValueAt(j,0);
                              hour = (String)jtabDados.getValueAt(j,1);
                              if ( (date != null && hour != null && data[0] != null) &&
                                      (date.trim().compareTo("") != 0 && hour.trim().compareTo("") != 0) ) {
                                  date = date.trim();
                                  hour = hour.trim();
                                  data[0] = data[0].trim();

                                  data[1] = "TO_DATE('" +
                                          dbinterface.formatDate((String)jtabDados.getValueAt(j,0),
                                                                (String)jcmbDate.getSelectedItem(),expt) +
                                          "','YYYY-MM-DD HH:MI:SS')";
                                  data[2] = (String)jtabDados.getValueAt(j,1);
                                  data[2] = data[2].substring(0, 5);
                                  data[2] = "'"+data[2]+"'";
                                  data[3] = (String)jtabDados.getValueAt(j, k);
                                  data[4] = dbinterface.getDateNum(date, (String)jcmbDate.getSelectedItem(),expt);
                                  if ( data[3] != null ) {
                                      data[3] = data[3].replace(',', '.');
                                      data[3] = data[3].trim();
                                      dbinterface.insert(currentNo.getTable(), cols, data, exins);
                                      valid ++;
                                          }
                              }
                       }
                    }
                    JOptionPane.showMessageDialog(null, "Foram inseridas " + (valid - exins.getSQLQueryErrCount()) + " tuplas.\n"
                            + "Exceções de dados: \n" + expt.toString() + "Exceções do SGBD :\n" + exins.toString());
                    expt.reset();
                    TableUtils.removeAllContent(jtabDispositivos);
                    TableUtils.deselectAll(jtabDados);
                    contentControler.getListControler().addAllContent(jlstRmDispositivos);
                    }
                    
                } else JOptionPane.showMessageDialog(null, "Você deve primeiro selecionar o "+
                                                    "formato de data que se enquadra em seus dados.");
            }
            
            if ( e.getSource() == jmenuAbrir )
                openFile();
            
            if ( e.getSource() == jmenuFechar ) {
                TableUtils.removeAllContent(jtabDados);
                ListUtils.removeAllContent(jlstRmDispositivos);
                TableUtils.removeAllContent(jtabDispositivos);
                contentControler.close();
            }
            
            if ( e.getSource() == jmenuSair ) {
                close();
            }
            
            if ( e.getSource() == jmenuAbrirConexao ) {
                ConnectionFrame connFrame = new ConnectionFrame(getMainFrame());
                connFrame.setVisible(true);
                
            }
            
            if ( e.getSource() == jmenuFecharConexao ) {
                currentNo.reset();
                for ( int i = 0; i < canais.length; i++ ) canais[i].reset();
                rmConnectionData();
                dbinterface.close();
            }
            
            if (e.getSource() == jmenuMask ) {
                ParseFrame parseFrame = new ParseFrame(getMainFrame());
                parseFrame.setVisible(true);
            }
            
            if (e.getSource() == jmenuRemover ) {
                if (currentNo != null && !currentNo.isEmpty()) {
                    FilterFrame filterFrame = new FilterFrame(getMainFrame());
                    filterFrame.setVisible(true);
                } else 
                    JOptionPane.showMessageDialog(null, "Você deve escolher uma tabela de dados para poder filtrar os mesmos.");
            }
            
            if (e.getSource() == jmenuAjuda ) {
                HelpFrame helpFrame = new HelpFrame();
                helpFrame.show();
            }

        }
    }
    
    /**
     * Desliga o aplicativo
     */
    public void close() {
        dbinterface.close();
        rmConnectionData();
        this.dispose();
        System.exit(0);
    }
    
    /**
     * Configura a conexão com a base de dados
     * @param ip IP em que se encontra o banco de dados
     * @param port Porta a qual o serviço de banco de dados está "escutando"
     * @param usr Usuário registrado que está requisitando acesso à base de dados
     * @param pass Senha do respectivo usuário
     * @param dataBase Base de dados a ser acessada
     */
    public void configDB( String ip, String port, String usr, String pass, String dataBase ) {
        
        dbinterface.start(ip, port, usr, pass, dataBase);
        DBCanal canal = new DBCanal(1);
        canal.inDatabase(dbinterface.getConn(), "SOL1");
        DBDispositivo disp = new DBDispositivo(canal.getCod());
        disp.inDatabase(dbinterface.getConn());
        DBNo no = new DBNo(35);
        no.inDatabase(dbinterface.getConn());

        DBNo [] nos = DBNo.allFromDatabase(dbinterface.getConn());

        DBCanal [] canais = DBCanal.allFromDatabase(dbinterface.getConn(), "SOL1");
        
    }
    
    /**
     * Configura combo box que conterá as tabelas de dados
     */
    public void configDBCombo() {
        DBNo [] nos = DBNo.allFromDatabase(dbinterface.getConn());
        String [] modelStr = new String[nos.length+1];

        modelStr[0] = "";

        for ( int i = 1; i < modelStr.length; i++ )
        modelStr[i] = String.valueOf(nos[i-1].getId()) + ":    " +
        nos[i-1].getCod() + ":    " + nos[i-1].getTable();
        
        ComboControler cmbControler = contentControler.getComboControler();
        cmbControler.setContent(jcmbNo, modelStr);

        jtabCanais.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod. Dispositivo", "Rótulo", "Canal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        
    }
    
    /**
     * Remove dados recebidos da base de dados
     */
    private void rmConnectionData() {
        ComboControler cmbControler = contentControler.getComboControler();
        String [] empty = { "" };
        cmbControler.setContent(jcmbNo, empty);
        jtabCanais.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod. Dispositivo", "Rótulo", "Canal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TableUtils.removeAllContent(jtabDispositivos);
        TableUtils.deselectAll(jtabDados);
        contentControler.getListControler().addAllContent(jlstRmDispositivos);
    }
    /**
     * Adiciona máscara de divisão de dados
     * @param s Caractere de divisão de dados
     */
    public void addMask(Character s) {
        parseMask.add(s);
    }
    
    /**
     * Remove máscara de divisão de dados
     * @param s Caractere de divisão de dados
     */
    public void removeMask(Character s) {
        parseMask.remove(s);
    }
    
    public ParseMaskControler getMask() {
        return parseMask;
    }
    
    public DBInterface getDBInterface() {
        return dbinterface;
    }
    
    public DBNo getCurrentNo() {
        return currentNo;
    }
    
}
